import React, {Component} from 'react';
import GoBack from "@/components/TheGoBack";
import TheImage from '@/components/TheImage';
import TheUpload from "@/components/TheUpload";
import TheDialog from "@/components/TheDialog";
import {
    Form,
    Typography,
    Select,
    Input,
    DatePicker,
    Space,
    Button,
    Radio,
    Row,
    Col,
    message,
    Timeline,
} from "antd";
import {
    apiGetMemberPhone,
    apiGetMemberByPhone,
    apiAddOperatorDynamic,
    apiGetDynamicDetail, apiGetOperationLog, apiUpdateOperatorDynamic, apiDynamicLabelList
} from '@/request/petCircleUtil/dynamic'
import './style.scss'
import moment from 'moment';
import {isJsonString} from '@/utils/isJsonString.js'
import AliOssUpload from "./OSSUpload";

const {Title} = Typography;
const {Search} = Input;

class Add extends Component {
    constructor(props) {
        super(props);
        this.state = {
            btnLoading: false,
            petDynamicId: null,
            disEdit: false,
            mode: '',
            phoneList: [],
            tagsList: [],
            imgFileList: [],
            videoFileList: [],
            logList: [],
            initialValues: {
                fileType: 1
            },
            visible: false,
            url: `https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&coord=45.80216%2C126.5358&key=ZYPBZ-NQNLF-HHUJC-NVLRM-OFL3Q-EBBL2&referer=myapp`
        };
    }

    componentDidMount = async () => {
        const {id, type} = this.props.match.params
        // await this.getPhoneList()
        await this.getTagsList()
        if (type !== 'create') {
            await this.getDynamicDetail(id)
            await this.getOperationLog(id)
        }
        this.setState({
            petDynamicId: id,
            mode: type
        })
        message.config({
            top: 110,
            // maxCount: 2
        });
        // 地图监听
        const _that = this;
        window.addEventListener("message", function (event) {
            if (event) {
                console.log(event)
                let mapData = {}
                if (event.data.latlng) {
                    mapData.lat = `${event.data.latlng.lat}`.substring(
                        0,
                        `${event.data.latlng.lat}`.indexOf(".") + 7
                    );
                    mapData.lon = `${event.data.latlng.lng}`.substring(
                        0,
                        `${event.data.latlng.lng}`.indexOf(".") + 7
                    );
                }
                mapData.city = event.data.cityname
                mapData.address = event.data.poiaddress
                mapData.locationName = event.data.poiaddress
                mapData.province = event.data.poiaddress.split(event.data.cityname)[0]
                if (mapData.province === '') {
                    mapData.province = mapData.city
                }
                // console.log(mapData)
                _that.setState(
                    {
                        mapData
                    }
                );
            }
        });
    }
    // 手机号码列表
    getPhoneList = async (value) => {
        const res = await apiGetMemberPhone({phone: value})
        if (res.code === 0 && res.data) {
            return res.data.map(item => {
                return {
                    label: item,
                    value: item
                }
            })
            // this.setState({
            //     phoneList: res.data.map(item => {
            //         return {
            //             label: item,
            //             value: item
            //         }
            //     })
            // })
        }
    }
    // 动态标签列表
    getTagsList = async () => {
        const res = await apiDynamicLabelList()
        if (res.code === 0 && res.data) {
            this.setState({
                tagsList: res.data.map(item => {
                    return {
                        label: item.labelName,
                        value: item.labelId
                    }
                })
            })
        }
    }
    // 动态详情
    getDynamicDetail = async (petDynamicId) => {
        const res = await apiGetDynamicDetail({petDynamicId})
        if (res.code === 0 && res.data) {
            this.formRef.setFieldsValue({
                ...res.data,
                labelIds: res.data.labelList.map(item => (item.labelId)),
                ip: (res.data.province ?? "") + (res.data.address ?? "")
            })
            let imgFileList = [], videoFileList = []
            if (isJsonString(res.data.fileUrl)) {
                if (res.data.fileType === 1) {
                    imgFileList = JSON.parse(res.data.fileUrl).image.map((v, i) => {
                        return {
                            uid: -i,
                            name: '预览',
                            status: 'done',
                            url: v.url
                        }
                    })
                } else {
                    videoFileList = JSON.parse(res.data.fileUrl).video.map((v, i) => {
                        return {
                            uid: new Date().getTime(),
                            name: '预览',
                            status: 'done',
                            url: v.url + "?x-oss-process=video/snapshot,t_1000,m_fast"
                        }
                    })
                }
            }
            // 判断当前时间是否大于发布预设时间
            let a = moment(), b = moment(res.data.expectReleaseTime), disEdit
            disEdit = a.diff(b) > 0;
            let mapData = {}
            if (res.data.province) {
                mapData.city = res.data.city
                mapData.address = res.data.address
                mapData.locationName = res.data.locationName
                mapData.province = res.data.province
                mapData.lat = res.data.lat
                mapData.lon = res.data.lon
            }
            this.setState({
                memberAvatar: res.data.memberAvatar,
                nickName: res.data.nickName,
                imgFileList, videoFileList,
                disEdit,
                mapData
            })
        }
    }
    // 操作日志
    getOperationLog = async (dataId) => {
        const res = await apiGetOperationLog({
            dataId,
            dataType: 1
        })
        if (res.code === 0 && res.data) {
            this.setState({
                logList: res.data
            })
        }
    }
    // 获取用户信息
    getMemberByPhone = async (value, event) => {
        this.formRef.validateFields(["phone"])
        let regExp = /^1(1|2|3|4|5|6|7|8|9)\d{9}$/g
        if (regExp.test(value)) {
            // let phone = this.formRef.getFieldValue('phone')
            if (value && value.toString().length === 11) {
                const res = await apiGetMemberByPhone({phone: value})
                if (res.code === 0 && res.data) {
                    this.setState({
                        ...res.data
                    })
                } else {
                    message.error(`无手机号:${value}信息,请重新输入`)
                    this.setState({
                        memberAvatar: '',
                        nickName: ''
                    })
                    this.formRef.resetFields(["phone"])
                }
            } else {
                message.error("请输入正确的号码")
            }
        }
    }
    // 表单字段值更新时触发回调事件
    onValuesChange = async (changedValues) => {
        // console.log(changedValues, 'changedValues')
        if ("phone" in changedValues) {
            if (changedValues.phone && changedValues.phone.toString().length === 11) {
                await this.getMemberByPhone(changedValues.phone)
            }
        }
        if ("fileType" in changedValues) {
            let {imgFileList, videoFileList} = this.state
            this.formRef.resetFields(["fileUrl"])
            if (changedValues.fileType === 1 && imgFileList.length > 0) {
                await this.getDetailsFileResult(imgFileList, 'imgFileList')
            }
            if (changedValues.fileType === 2 && videoFileList.length > 0) {
                await this.getDetailsFileResult(videoFileList, 'videoFileList')
            }
        }
    }

    // 抓取表单验证失败提示
    onFinishFailed(values) {
        console.log(values, '抓取表单验证失败提示:onFinishFailed');
        if (values.errorFields.length > 0) {
            React.$message({
                type: 'warn',
                content: values.errorFields[0].errors[0]
            })
        }
    }

    //form表单确定事件
    onFinish = async (values) => {
        console.log(values, '提交数据')
        // if (this.state.memberAvatar===undefined &&this.state.nickName===undefined ){
        //     message.error("请搜索用户信息")
        // }
        // 判断发布预设时间是否大于当前时间
        let a = moment(), b = moment(values.expectReleaseTime)
        if (a.diff(b) > 0) {
            message.error("预计发布时间不可小于当前时间")
            return
        }
        let {mode, petDynamicId, mapData} = this.state
        this.setState({
            btnLoading: true
        })
        let params = {...values, ...mapData}
        if (mode === 'create') {
            const res = await apiAddOperatorDynamic({...params})
            if (res.code === 0) {
                message.success('添加成功')
                this.props.history.goBack()
            } else {
                this.setState({
                    btnLoading: false
                })
            }
        } else {
            const res = await apiUpdateOperatorDynamic({
                ...params, petDynamicId
            })
            if (res.code === 0) {
                message.success('修改成功')
                this.props.history.goBack()
            } else {
                this.setState({
                    btnLoading: false
                })
            }
        }
    }
    // 获取上传图片|视频数据
    loadImage = (url, type) => {
        return new Promise(async (resolve) => {
            let img = new Image()
            if (type === 2) {
                // 通过视频封面获取数据
                img.src = url + "?x-oss-process=video/snapshot,t_1000,m_fast"
            } else {
                img.src = url
            }
            img.onload = async () => {
                let ratio = ''
                if (img.width === img.height) {
                    ratio = '1:1'
                }
                if (img.width > img.height) {
                    ratio = '4:3'
                }
                if (img.width < img.height) {
                    ratio = '3:4'
                }
                await resolve({
                    width: img.width,
                    height: img.height,
                    url,
                    ratio,
                })
            }
        })
    }
    // 上传文件回调
    getDetailsFileResult = async (value, key) => {
        let type = this.formRef.getFieldValue("fileType")
        if (value && value.length) {
            Promise.all(
                value.map(v => {
                    if (v.response && v.response.code === 200) {
                        return this.loadImage(v.response.data, type)
                    } else {
                        return this.loadImage(v.url, type)
                    }
                })
            ).then(res => {
                if (type === 1) {
                    this.formRef.setFieldsValue({
                        "fileUrl": JSON.stringify({
                            image: res
                        })
                    })
                } else {
                    this.formRef.setFieldsValue({
                        "fileUrl": JSON.stringify({
                            video: res
                        })
                    })
                }
            })
            this.setState({
                [key]: value
            })
        } else {
            this.formRef.resetFields(["fileUrl"])
            this.setState({
                [key]: []
            })
        }
    }
    // 可领时间 禁止选择当天之前时间
    range = (start, end) => {
        const result = [];
        for (let i = start; i <= end; i++) {
            result.push(i);
        }
        return result;
    };
    disabledDate = (current) => {
        return current && current < moment().startOf('day');
    };
    // 判断发布预设时间是否大于当前时间
    onOkChange = (value) => {
        let a = moment(), b = moment(value)
        if (a.diff(b) > 0) {
            message.error("预计发布时间不可小于当前时间,请重新选择")
            this.formRef.resetFields(["expectReleaseTime"])
        }
    }
    openDialog = () => {
        this.setState({
            visible: true
        })
    }
    handleCancel = () => {
        this.setState({
            visible: false,
        });
    }
    handleOk = () => {
        const {mapData} = this.state;
        if (mapData) {
            console.log(mapData)
            this.formRef.setFieldsValue(mapData)
            this.handleCancel()
        }
    }

    render() {
        let {
            initialValues,
            phoneList,
            tagsList,
            imgFileList,
            videoFileList,
            btnLoading,
            memberAvatar,
            nickName,
            logList,
            disEdit,
            visible,
            url
        } = this.state
        let title = '', mode = this.props.match.params.type
        switch (mode) {
            case "create":
                title = "新建动态"
                break;
            case "view":
                title = "查看动态"
                break;
            case "edit":
                title = "修改动态"
                break;
            default:
                break;
        }
        return (
            <Row>
                <Col span={mode === 'create' ? 24 : 18}>
                    <div className={"p-layout-box"}>
                        <GoBack history={this.props.history} title={title}/>
                        <Form
                            onFinish={this.onFinish}
                            ref={ref => this.formRef = ref}
                            labelCol={{
                                span: 3
                            }}
                            wrapperCol={{
                                span: 8,
                            }}
                            onFinishFailed={this.onFinishFailed}
                            onValuesChange={this.onValuesChange}
                            initialValues={initialValues}
                            className={mode}
                        >
                            <Title level={4} className={'f-title'}>基本信息</Title>
                            {mode !== 'view' && <Form.Item label={"用户手机号"}
                                                           name="phone"
                                                           rules={[{
                                                               required: true,
                                                               message: '请输入正确的手机号',
                                                               pattern: new RegExp(/^1(1|2|3|4|5|6|7|8|9)\d{9}$/, "g")
                                                           }]}
                            >
                                {
                                    mode === 'edit' ? <Input disabled={true} bordered={false}/> : <Input
                                        placeholder="请输入11位手机号码"
                                        // onSearch={this.getMemberByPhone}
                                        style={{
                                            width: 300,
                                        }}
                                        maxLength={11}
                                    />
                                }
                            </Form.Item>}
                            <Form.Item label="用户昵称">
                                <span className="ant-form-text">{nickName}</span>
                            </Form.Item>
                            <Form.Item label="用户头像">
                                <span className="ant-form-text">
                                    <TheImage preview={false} src={memberAvatar} width={80} height={80}/>
                                </span>
                            </Form.Item>
                            <Title level={4} className={'f-title'}>动态信息</Title>
                            <Form.Item rules={[
                                {required: true},
                                ({getFieldValue}) => ({
                                    validator(_, value) {
                                        const regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[A9|AE]\u3030|uA9|uAE|\u3030/gi
                                        if (!regStr.test(value)) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error("不可添加表情"));
                                    },
                                }),
                            ]}
                                       label="动态标题" name="dynamicTitle">
                                <Input allowClear maxLength={20}
                                       showCount={mode !== 'view'}
                                       disabled={mode === 'view' || disEdit}
                                       bordered={mode !== 'view'}/>
                            </Form.Item>
                            <Form.Item label="动态内容" name="dynamicText">
                                <Input.TextArea rows={4} allowClear maxLength={2000}
                                                showCount={mode !== 'view'}
                                                disabled={mode === 'view' || disEdit}
                                                bordered={mode !== 'view'}/>
                            </Form.Item>
                            {
                                mode !== 'view' &&
                                <Form.Item rules={[{required: true}]} label="文件类型" name="fileType">
                                    <Radio.Group disabled={disEdit}>
                                        <Radio value={1}>图片</Radio>
                                        <Radio value={2}>视频</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            }
                            <Form.Item noStyle shouldUpdate>
                                {({getFieldValue}) => <>
                                    {
                                        getFieldValue("fileType") === 1 &&
                                        <Form.Item rules={[{required: true, message: "请上传图片"}]} label="图片"
                                                   name="fileUrl" extra={"单图片大小最大为20M"}>
                                            <AliOssUpload accept={['image/jpg', 'image/jpeg', 'image/png']} maxSize={20}
                                                          fileType={'image'}
                                                          fileList={imgFileList}
                                                          isDrop={mode !== 'view'}
                                                          getFileResult={(e) => this.getDetailsFileResult(e, 'imgFileList')}
                                                          isShowRemoveIcon={mode === 'create' || (mode === 'edit' && !disEdit)}
                                                          len={mode === 'view' || disEdit ? imgFileList.length : 9}/>
                                        </Form.Item>
                                    }
                                    {
                                        getFieldValue("fileType") === 2 &&
                                        <Form.Item rules={[{required: true, message: "请上传视频"}]} label="视频"
                                                   name="fileUrl" extra={"请上传MP4格式,视频文件大小最大为300M"}>
                                            <AliOssUpload accept={['video/mp4']} maxSize={300} fileType={'video'}
                                                          fileList={videoFileList}
                                                          isDrop={false}
                                                          getFileResult={(e) => this.getDetailsFileResult(e, 'videoFileList')}
                                                          isShowRemoveIcon={mode === 'create' || (mode === 'edit' && !disEdit)}
                                                          len={1}/>
                                        </Form.Item>
                                    }
                                </>}
                            </Form.Item>
                            <Form.Item label={"动态标签"} name="labelIds">
                                <Select
                                    showSearch
                                    mode="multiple"
                                    options={tagsList}
                                    disabled={mode === 'view' || disEdit}
                                    bordered={mode !== 'view'}
                                    filterOption={(input, option) =>
                                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                    }
                                    placeholder={mode === 'view' ? "" : "请选择"}
                                />
                            </Form.Item>
                            <Form.Item label={"省/直辖市"}>
                                <Row gutter={8}>
                                    <Col flex="auto">
                                        <Form.Item
                                            name={'province'}
                                            noStyle
                                        >
                                            <Input disabled placeholder={mode === 'view' ? "" : "通过地图选择获取"}/>
                                        </Form.Item>
                                    </Col>
                                    <Col flex="90px">
                                        <Button disabled={mode === 'view'} type="primary"
                                                onClick={this.openDialog}>打开地图</Button>
                                    </Col>
                                </Row>
                            </Form.Item>
                            <Form.Item
                                label={"具体地址"}
                                name={'address'}
                            >
                                <Input disabled placeholder={mode === 'view' ? "" : "通过地图选择获取"}/>
                            </Form.Item>
                            {
                                mode !== 'view' && <>
                                    <Title level={4} className={'f-title'}>定时任务</Title>
                                    <Form.Item label="预计发布时间" name="expectReleaseTime"
                                               rules={[{required: true, message: '请选择预计发布时间'}]}
                                               getValueProps={v => ({value: v ? moment(v) : null, v})}
                                               getValueFromEvent={e => e ? moment(e).format('YYYY-MM-DD HH:mm:ss') : e}
                                    >
                                        <DatePicker
                                            showTime
                                            format="YYYY-MM-DD HH:mm:ss"
                                            showNow={false}
                                            disabled={disEdit}
                                            disabledDate={this.disabledDate}
                                            onOk={this.onOkChange}
                                            // open={true}
                                            // disabledTime={this.disabledDateTime}
                                        />
                                    </Form.Item>
                                    <Form.Item label="备注" name="remark">
                                        <Input.TextArea rows={2} allowClear disabled={disEdit}/>
                                    </Form.Item>
                                </>
                            }
                            {
                                mode === 'view' && <>
                                    <Form.Item label="ip定位" name="ip">
                                        <Input disabled bordered={false}/>
                                    </Form.Item>
                                    <Form.Item label="点赞数" name="likeNum">
                                        <Input disabled bordered={false}/>
                                    </Form.Item>
                                    <Form.Item label="评论数" name="comments">
                                        <Input disabled bordered={false}/>
                                    </Form.Item>
                                    <Form.Item label="转发数" name="shareNum">
                                        <Input disabled bordered={false}/>
                                    </Form.Item>
                                    <Title level={4} className={'f-title'}>其他信息</Title>
                                </>
                            }
                            {
                                (mode === 'view' || mode === 'edit') && <Form.Item shouldUpdate noStyle>
                                    {({getFieldValue}) => {
                                        return <Form.Item
                                            name="linkUrl"
                                            label="动态对应链接"
                                            wrapperCol={{
                                                span: 20,
                                            }}
                                        >
                                            <Typography.Text copyable>{getFieldValue('linkUrl')}</Typography.Text>
                                        </Form.Item>
                                    }}
                                </Form.Item>
                            }
                            {
                                mode === 'view' || disEdit ? [] : <Form.Item
                                    wrapperCol={{
                                        offset: 6,
                                        span: 16,
                                    }}
                                >
                                    <Space>
                                        <Button onClick={() => this.props.history.goBack()}>取消</Button>
                                        <Button loading={btnLoading} htmlType="submit" type="primary">保存</Button>
                                    </Space>
                                </Form.Item>
                            }
                        </Form>
                    </div>
                </Col>
                {
                    (mode === 'view' || mode === 'edit') && <Col span={6} className={'side'}>
                        <div className={"p-layout-box"}>
                            <div style={{marginBottom: '1em'}}>操作日志</div>
                            <Timeline>
                                {
                                    logList.map(item => {
                                        return <Timeline.Item color="gray" key={item.operationUser}>
                                            <div>{item.info}</div>
                                            <span
                                                className={'side-span'}>{item.operationUserName}</span><span>{item.operationTime}</span>
                                        </Timeline.Item>
                                    })
                                }
                            </Timeline>
                        </div>
                    </Col>
                }
                <TheDialog
                    title=""
                    width={500}
                    handleCancel={this.handleCancel}
                    handleOk={this.handleOk}
                    visible={visible}
                >
                    <iframe
                        title="map"
                        style={{
                            width: 400,
                            height: 700,
                            border: "1px solid #fafafa",
                            marginLeft: "20px",
                        }}
                        src={url}
                    />
                </TheDialog>
            </Row>
        );
    }
}

export default Add;
